package com.megagoodsoftware.MediaShare;

//import com.megagoodsoftware.MediaShare.R.layout;

import java.io.*;
import java.util.*;

import android.app.*;
import android.content.*;
import android.net.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;

import com.megagoodsoftware.smugmug.*;
import com.megagoodsoftware.smugmug.CountingHttpEntity.*;
import com.megagoodsoftware.smugmug.exceptions.*;
import com.megagoodsoftware.smugmug.util.*;

/**
 * Activity used to display a Flickr user's photostream. This activity shows a
 * fixed number of photos at a time. The activity is invoked either by
 * LoginActivity, when the application is launched normally, or by a Home
 * shortcut, or by an Intent with the view action and a flickr://photos/nsid
 * URI.
 */
public class MediaShareActivity extends Activity {

	static final String ACTION = "com.megagoodsoftware.MediaShare.FLICKR_STREAM";

	static final String EXTRA_NOTIFICATION = "com.megagoodsoftware.MediaShare.extra_notify_id";
	static final String EXTRA_NSID = "com.megagoodsoftware.MediaShare.extra_nsid";
	static final String EXTRA_USER = "com.megagoodsoftware.MediaShare.extra_user";

	private static final String STATE_USER = "com.megagoodsoftware.MediaShare.state_user";
	private static final String STATE_PAGE = "com.megagoodsoftware.MediaShare.state_page";
	private static final String STATE_PAGE_COUNT = "com.megagoodsoftware.MediaShare.state_pagecount";

	private User mUser;
	private AsyncTask<?, ?, ?> mTask;
	private String mUsername;
	private SmugMug sm;
	private String mAlbum;
	private ProgressBar bar;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		clearNotification();

		// Try to find a user name in the saved instance state or the intent
		// that launched the activity. If no valid user NSID can be found, we
		// just close the activity.
		if (!initialize(savedInstanceState)) {
			finish();
			return;
		}

		setContentView(R.layout.screen_photostream);
		
		Intent it = new Intent(this, UploadService.class);
		it.putExtras(getIntent().getExtras());
		it.putExtra("SM_ALBUM", mAlbum);
		it.putExtra("SM_ID", mUser.getId());
		it.putExtra("SM_PASSWORD", mUser.getPassword());
		//SmugMugAccount ac = sm.getAccount();
		//it.putExtra("SM_ACCOUNT", ac);
		startService(it);
		Toast.makeText(MediaShareActivity.this,
				"Upload Initiated, Please check your Notifications", Toast.LENGTH_LONG)
				.show();

		finish();
	}

	private void uploadToSmugMug() {

		//mTask = new UploadSMPhotoTask().execute(extras);
	}

	private void clearNotification() {
		final int notification = getIntent()
				.getIntExtra(EXTRA_NOTIFICATION, -1);
		if (notification != -1) {
			NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			manager.cancel(notification);
		}
	}

	/**
	 * Starts the PhotostreamActivity for the specified user.
	 * 
	 * @param context
	 *            The application's environment.
	 * @param string
	 *            The user whose photos to display with a PhotostreamActivity.
	 */
	static void show(Context context, String string) {
		final Intent intent = new Intent(ACTION);

		intent.putExtras(((Activity) context).getIntent());
		intent.putExtra(SmugMugBundleHelper.EXTRA_ALBUM, string);
		context.startActivity(intent);
	}

	/**
	 * Restores a previously saved state or, if missing, finds the user's NSID
	 * from the intent used to start the activity.
	 * 
	 * @param savedInstanceState
	 *            The saved state, if any.
	 * 
	 * @return true if a {@link com.megagoodsoftware.MediaShare.User} was found
	 *         either in the saved state or the intent.
	 */
	private boolean initialize(Bundle savedInstanceState) {
		User user;
		if (savedInstanceState != null) {
			user = savedInstanceState.getParcelable(STATE_USER);
			savedInstanceState.getInt(STATE_PAGE);
			savedInstanceState.getInt(STATE_PAGE_COUNT);
		} else {
            final Intent intent = getIntent();

            user = SmugMugBundleHelper.getUserFromBundle(intent);
            mAlbum = SmugMugBundleHelper.getAlbumFromBundle(intent);
		}
		mUser = user;
		return (mUser != null && mAlbum != null) || mUsername != null;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		outState.putParcelable(STATE_USER, mUser);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mTask != null && mTask.getStatus() == AsyncTask.Status.RUNNING) {
			mTask.cancel(true);
		}
	}

	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case 0: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage("Please wait while loading...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
        }
		return null;
    }

 	private boolean uploadTarget(final UploadSMPhotoTask uploadSMPhotoTask, Uri target) {
		InputStream md5is = null;
		InputStream in = null;
		try {
			final MediaShareFile file = new MediaShareFile(getContentResolver(), target);
			// need to open a separate input stream to get the md5sum
			md5is = file.openInputStream();
			in = file.openInputStream();
			System.out.println("file size = " + file.getSize());
			final ProgressBar bar = (ProgressBar) findViewById(R.id.progress);
			bar.setIndeterminate(false);
			bar.setMax(101);

			//uploadSMPhotoTask.publishProgress(new Integer(-5));
			ProgressListener listener = new ProgressListener() {
				
				@Override
				public void transferred(int num) {
					System.out.println("num = " + num);
					int percent = (int)(((float)num/file.getSize()) * 100);
					bar.setProgress(percent);
					//uploadSMPhotoTask.publishProgress(new Integer(percent));
				}
			};
			
			sm = new SmugMug(Integer.parseInt(mUser.getId()), mUser
					.getPassword());
			Log.i(Constants.TAG, sm.getAccount().toString()); 

			sm.upload(listener, in, SmugMugUtil.getMd5Hash(md5is), sm.getAlbums(mAlbum).get(0),
					file.getName());
			//uploadSMPhotoTask.publishProgress(new Integer(101));
			bar.setProgress(101);
			return true;
		} catch (SmugMugConnectionError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SmugMugFailedResponse e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SmugMugInternalError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			Log.d(Constants.TAG, "Unexpected exception: " + e);
		} finally {
			try {
				md5is.close();
				in.close();
			} catch (IOException e) {
				Log.w(Constants.TAG, "Unable to close connection: " + e);
			}
		}
		return false;
	}

	/**
	 * Background task used to load the list of photos. The tasks queries Flickr
	 * for the list of photos to display and ends by starting the
	 * LoadPhotosTask.
	 */
	private class UploadSMPhotoTask extends AsyncTask<Bundle, Integer, Boolean> {
		public Boolean doInBackground(Bundle... params) {
			Bundle extras = params[0];
			boolean retVal = false;
			if (extras != null) {
				Object o = extras.get(Intent.EXTRA_STREAM);
				if (o instanceof Uri) {
					Uri target = (Uri) o;
					retVal = uploadTarget(this, target);
				} else if (o instanceof ArrayList<?>) {
					ArrayList<?> uris = (ArrayList<?>) o;
					for (Iterator<?> it = uris.iterator(); it.hasNext(); ){
						retVal |= uploadTarget(this, (Uri)it.next());
					}
				}
			}
			return retVal;
        }

		@Override
		public void onProgressUpdate(Integer... values) {
			int i = values[0].intValue();
			switch(i) {
			case -5:
				bar.setIndeterminate(false);
				bar.setVisibility(View.VISIBLE);
				break;
			default:
				bar.setProgress(i);
				break;
			}
		}

		@Override
		public void onPostExecute(Boolean result) {
			mTask = null;
			if (result == true) {
				Toast.makeText(MediaShareActivity.this,
						R.string.success_file_upload, Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(MediaShareActivity.this,
						R.string.failure_file_upload, Toast.LENGTH_SHORT)
						.show();
			}
			finish();
		}
	}
}
